# import json
import json
import logging

from apps.settingApi.api.timerTask.apiList.jdYxk.utils import yxkApiList
from apps.settingApi.api.timerTask.apiList.logsAdd import add
from apps.settingApi.api.timerTask.apiList.wmsapiUtils import wmsApiList
# from apps.settingApi.api.timerTask.apiList.wmsapiUtils import wmsApiList
from comm.dbConnect import dbListJon, dbJonOne, dbEdit, get_yun_session
from comm.openDbConfig import openDbBase


# from comm.openDbConfig import openDbBase


# 送检入库----暂时无用
# def jdYxkErpApiPrdt():
def jdYxkErpApiPrdt(db, taskObj):
    print('yxkapiErp-Wms')

    for i in range(1000):
        logData = {}
        logData['status'] = True
        logData['name'] = taskObj["name"]
        logData['order'] = ""
        logData['data'] = ""
        logData['rem'] = ""
        yxkPrdt, err = yxkApiList.partBatGet({"pageSize": 10, "pageNo": i + 1})
        print(i + 1, yxkPrdt)
        if err is not None:
            logData['status'] = False
            logData['rem'] = "推送" + str(i + 1) + "数据查询失败" + err
            add(db, logData)
            continue

        for row in yxkPrdt['data']:
            # 查询物料是否存在
            sql1 = "select prd_no from prdt where prd_no=:prd_no"
            dataBin, err = dbJonOne(sql=sql1, engineName=None, parm={"prd_no": row['number']}, db_session=db)
            if err != None:
                logData['status'] = False
                logData['rem'] = '查询查询物料失败' + sql1 + err
                add(db, logData)
                continue
            print(dataBin)
            prdtData = {
                "owner_code": "OWNER",
                "item_code": row['number'],
                "item_name": row['name'],
                "specifications": row['modelnum'],
                "batch_control": "T",
                "unit_name": row["baseunit_name"],
                "item_properties": "002",
            }
            if dataBin is None:
                _, err = wmsApiList.addPrdt(prdtData)
                logData['status'] = False
                logData['data'] = json.dumps(prdtData, ensure_ascii=False)
                logData['rem'] = '新增失败' + err
                add(db, logData)
            else:
                _, err = wmsApiList.updatePrdt(prdtData)
                logData['status'] = False
                logData['data'] = json.dumps(prdtData, ensure_ascii=False)
                logData['rem'] = '修改失败' + err
                add(db, logData)

        # 如果是最后一页则退出
        if yxkPrdt["lastPage"] == True:
            return
    #     # 获取token
    #     token,err = wmsApiList.getToken()
    #     if err != None:
    #         logData['status'] = False
    #         logData['rem'] = err
    #         add(db, logData)
    #         return
    #     # 查询拆分
    #     sql_select_bin = """
    # select a.bil_no as tz_no from mf_rk a WITH(NOLOCK)
    # left join mf_rk_z b WITH(NOLOCK)  on a.rk_no=b.rk_no
    # where isnull(b.pull_id,'')!='T'
    # group by a.bil_no
    #     """
    #
    #     sql_select_mf = """
    # select a.ru_no,a.*,b.* from mf_rk a WITH(NOLOCK)
    # left join mf_rktz b WITH(NOLOCK) on a.bil_no=b.tz_no
    # left join mf_rktz_z c WITH(NOLOCK)  on b.tz_no=c.tz_no
    # where a.bil_no=:tz_no
    #     """
    #     # 查询需要推送的数据
    #     sql_select = """
    # select c.u9cid,a.wh,sum(cast(isnull(a.qty,0) as float)) as qty ,a.bat_no,a.prd_no from tf_rk a WITH(NOLOCK)
    # left join tf_rktz_z b WITH(NOLOCK)  on a.bil_no=b.tz_no and a.bil_itm=b.itm
    # left join tf_rktz_z c WITH(NOLOCK)  on c.tz_no=b.tz_no and c.itm=b.itm where
    # where a.bil_no=:tz_no
    # group by c.u9cid,a.wh,a.bat_no,a.prd_no
    # """
    #     # 更新推送时间
    #     sql_u = "update mf_rk_z set pull_id='T' where rk_no=:rk_no"
    #
    #     dataBin, err = dbListJon(sql=sql_select_bin, engineName=None, parm={}, db_session=db)
    #     if err != None:
    #         logData['status'] = False
    #         logData['rem'] = '查询进货入库汇总' + sql_select_bin + err
    #         add(db, logData)
    #         return
    #     for itm_bin in dataBin:
    #
    #         # 1、查询需要推送的数据
    #         data, err = dbJonOne(sql=sql_select_mf, engineName=None, parm={"tz_no":itm_bin['tz_no']}, db_session=db)
    #         if err != None:
    #             logData['status'] = False
    #             logData['rem'] = '查询进货入库表头' + sql_select + err
    #             add(db, logData)
    #             return
    #
    #         # 更新推送标识
    #         _, err = dbEdit(sql=sql_u, engineName=None, parm=data, db_session=db)
    #         if err != None:
    #             logData['status'] = False
    #             logData['rem'] = '更新进货入库' + data["ru_no"] + '推送标识异常;' + err
    #             add(db, logData)
    #             continue
    #
    #
    #         # 查询表身需要推送的数据
    #         tf_data, err = dbListJon(sql=sql_select, engineName=None, parm=data, db_session=db)
    #         if err != None:
    #             logData['status'] = False
    #             logData['rem'] = '查询表身推送数据列表异常' + sql_select + err
    #             add(db, logData)
    #             return
    #         # 拼接数据
    #         addData = {}
    #
    #         logData['order'] = data["ru_no"]
    #
    #         logData['data'] = json.dumps(addData, ensure_ascii=False)
    #
    #         add(db, logData)
    return


def jdYxkWmsApiOsCk(db, taskObj):
    print('Wms-yxkapiErp')

    logData = {}
    logData['status'] = True
    logData['name'] = taskObj["name"]
    logData['order'] = ""
    logData['data'] = ""
    logData['rem'] = ""

    # 获取token
    token, err = wmsApiList.getToken()
    if err != None:
        logData['status'] = False
        logData['rem'] = err
        add(db, logData)
        return
    # 查询要推送的单据
    sql_select_bin = """
    select a.ck_no from mf_ck a WITH(NOLOCK)
    left join mf_ck_z b WITH(NOLOCK) on a.ck_no=b.ck_no 
    left join tf_ck c WITH(NOLOCK) on a.ck_no=c.ck_no
    where isnull(b.pull_id,'')!='T' and type_id='01' and isnull(a.erp_ap_no,'') != ''
        """
    # 查询头信息
    sql_select_mf = """
    select a.ck_no,convert(varchar(100), a.ck_dd, 23) as ck_dd,a.dep,a.rem,a.erp_ap_no,a.rem,
    b.def1,b.def10,b.def11,b.def2,b.def3,b.def4,b.def5,b.def6,b.def7,b.def8,b.def9,b.def12,b.def13,b.def14
    from mf_ck a with(nolock)
    left join mf_cktz_z b with(nolock) on a.bil_no=b.tz_no
    where a.ck_no=:ck_no
        """
    # 查询表身信息
    sql_select = """
    select a.wh,cast(isnull(a.qty,0) as float) as qty ,a.bat_no,a.prd_no,a.itm,a.rem,a.erp_ap_itm,
    c.def1,c.def2,c.def3,c.def4,c.def5 from tf_ck a WITH(NOLOCK)
    left join tf_cktz b WITH(NOLOCK) on a.bil_no=b.tz_no and a.bil_itm=b.itm 
    left join tf_cktz_z c WITH(NOLOCK) on c.tz_no=b.tz_no and c.itm=b.itm
    where a.ck_no=:ck_no
    """

    # 更新推送时间
    sql_u = "update mf_ck_z set pull_id='T' where ck_no=:ck_no"

    dataBin, err = dbListJon(sql=sql_select_bin, engineName=None, parm={}, db_session=db)
    if err != None:
        logData['status'] = False
        logData['rem'] = '查询wms销货出库单' + sql_select_bin + err
        add(db, logData)
        return
    for itm_bin in dataBin:

        # 1、查询需要推送的数据
        data, err = dbJonOne(sql=sql_select_mf, engineName=None, parm={"ck_no": itm_bin['ck_no']}, db_session=db)
        if err != None:
            logData['status'] = False
            logData['rem'] = '查询出库表头' + sql_select + err
            add(db, logData)
            return
        # 查询表身需要推送的数据
        tf_data, err = dbListJon(sql=sql_select, engineName=None, parm=itm_bin, db_session=db)
        if err != None:
            logData['status'] = False
            logData['rem'] = '查询表身推送数据列表异常' + sql_select + err
            add(db, logData)
            return
        # 拼接数据
        addData = []
        for itm_1 in tf_data:
            itm_data = {
                "SrcDocType": 2,
                "SrcDocNo": data['erp_ap_no'],
                "SrcDocLineNo": itm_1['erp_ap_itm'],
                "SrcDocSubLineNo": 0,
                "wh": 0,
                "WHCode": itm_1['wh'],
                "CurShipQty1": itm_1['qty'],
                "CurShipQty2": 0,
                "SOIsConsign": True,
                "OptionalSplitTerm": [],
                "DescFlexField": {},
                "LineDescFlexField": {},
                "ShipDate": data['ck_dd'],
                "ShipConfirmDate": data['ck_dd'],
                "ShipMemo": data['rem'],
                "ShipLineMemo": itm_1['rem'],
                "ShipDocTypeID": 0,
                "ShipDocTypeCode": 'SH1',
                "DocNo": data['ck_no']
            }
            addData.append(itm_data)

        logData['order'] = data["ck_no"]
        logData['data'] = json.dumps(addData, ensure_ascii=False)
        # 更新推送标识
        _, err = dbEdit(sql=sql_u, engineName=None, parm=data, db_session=db)
        if err != None:
            logData['status'] = False
            logData['rem'] = '更新入库单' + data["ck_no"] + err
            add(db, logData)
            continue
        # 调用云星空Api生成标准出库单
        u9c_, err = yxkApiList.osCkAddPost(addData)
        if err != None:
            logData['status'] = False
            logData['rem'] = '销货出库推送失败' + data["ck_no"] + err
            add(db, logData)
            continue
        logData['status'] = True
        logData['rem'] = json.dumps(u9c_, ensure_ascii=False)
        add(db, logData)
    return


def jdYxkWmsApiMORk(db, taskObj):
    print('Wms-yxkapiErp-生产入库')
    logData = {}
    logData['status'] = True
    logData['name'] = taskObj["name"]
    logData['order'] = ""
    logData['data'] = ""
    logData['rem'] = ""

    # 获取token
    token, err = wmsApiList.getToken()
    if err != None:
        logData['status'] = False
        logData['rem'] = err
        add(db, logData)
        return
    # 查询要推送的单据
    sql_select_bin = """
select a.type_id,a.rk_no from mf_rk a WITH(NOLOCK)
left join mf_rk_z b WITH(NOLOCK) on a.rk_no=b.rk_no 
left join tf_rk c WITH(NOLOCK) on a.rk_no=c.rk_no
left join my_wh d WITH(NOLOCK) on a.wh=d.wh
where 
--a.bil_no='UO251023000002' and 
isnull(b.pull_id,'')!='T' and type_id='04' and isnull(a.erp_ap_no,'') != '' and a.rk_no='RK251023000005'
and isnull(d.fax_no,'')!=''
        """

    # 查询头信息
    sql_select_mf = """
select a.rk_no,convert(varchar(100), a.rk_dd, 23) as rk_dd,a.dep,a.rem,a.erp_ap_no,a.rem
from mf_rk a with(nolock)
left join mf_rktz_z b with(nolock) on a.bil_no=b.tz_no
where a.rk_no=:rk_no
            """
    # 查询表身信息
    sql_select = """
select a.prd_mark,d.fax_no as wh,cast(isnull(a.qty,0) as float) as qty ,a.bat_no,a.prd_no,a.itm,a.rem,a.erp_ap_itm,
c.def1 from tf_rk a WITH(NOLOCK)
left join tf_rktz b WITH(NOLOCK) on a.bil_no=b.tz_no and a.bil_itm=b.itm 
left join tf_rktz_z c WITH(NOLOCK) on c.tz_no=b.tz_no and c.itm=b.itm
left join my_wh d WITH(NOLOCK) on a.wh=d.wh
where isnull(d.fax_no,'')!='' and a.rk_no=:rk_no
"""
    # 插入自定义表
    sql_z = """
INSERT INTO MF_RK_Z (RK_NO)
SELECT RK_NO FROM MF_RK
EXCEPT
SELECT RK_NO FROM MF_RK_Z;
    """
    # 更新推送时间
    sql_u = "update mf_rk_z set pull_id='T' where rk_no=:rk_no"
    # 插入自定义表数据
    _, err = dbEdit(sql=sql_z, engineName=None, parm={}, db_session=db)
    if err != None:
        logData['status'] = False
        logData['rem'] = '插入自定义表失败' + err
        add(db, logData)
        return
    dataBin, err = dbListJon(sql=sql_select_bin, engineName=None, parm={}, db_session=db)
    if err != None:
        logData['status'] = False
        logData['rem'] = '查询wms生产入库单' + sql_select_bin + err
        add(db, logData)
        return
    for itm_bin in dataBin:
        # 1、查询需要推送的数据
        data, err = dbJonOne(sql=sql_select_mf, engineName=None, parm={"rk_no": itm_bin['rk_no']}, db_session=db)
        if err != None:
            logData['status'] = False
            logData['rem'] = '查询入库表头' + sql_select + err
            add(db, logData)
            return
        # 查询表身需要推送的数据
        tf_data, err = dbListJon(sql=sql_select, engineName=None, parm=itm_bin, db_session=db)
        if err != None:
            logData['status'] = False
            logData['rem'] = '查询表身推送数据列表异常' + sql_select + err
            add(db, logData)
            return
        addData = {
            "data": [
                {
                    "billno": data["rk_no"],
                    "biztime": data["rk_dd"] + " 00:00:00",
                    "invscheme_number": "331",
                    "biztype_number": "330",
                    "billentry": [

                    ],
                }
            ]
        }
        billentry = []
        for itm_1 in tf_data:
            try:
                producedate = itm_1['bat_no'][0:4] + '-' + itm_1['bat_no'][4:6] + '-' + itm_1['bat_no'][6:8]
            except Exception as e:
                logging.info('入库单批号错误' + data["rk_no"] + ";批号为：" + itm_1['bat_no'] + repr(e))
                logData['status'] = False
                logData['rem'] = '入库单批号错误' + data["rk_no"] + ";批号为：" + itm_1['bat_no'] + repr(e)
                add(db, logData)
                return
            itm_data = {
                "material_number": itm_1['prd_no'],
                "lotnumber": itm_1["prd_mark"],
                "producedate": producedate,
                "invtype_number": "110",
                "invstatus_number": "110",
                "manubill": itm_1["def1"],
                "warehouse_number": itm_1["wh"],
                "qty": itm_1["qty"]
            }
            billentry.append(itm_data)
        addData["data"][0]["billentry"] = billentry
        logData['order'] = data["rk_no"]
        logData['data'] = json.dumps(addData, ensure_ascii=False)
        # 更新推送标识
        _, err = dbEdit(sql=sql_u, engineName=None, parm=data, db_session=db)
        if err != None:
            logData['status'] = False
            logData['rem'] = '更新入库单' + data["rk_no"] + err
            add(db, logData)
            continue
        # 调用云星空Api生成完工入库单
        u9c_, err = yxkApiList.moRkAddPost(addData)
        if err != None:
            logData['status'] = False
            logData['rem'] = '生产入库单推送失败' + data["rk_no"] + err
            add(db, logData)
            continue
        logData['status'] = True
        logData['rem'] = json.dumps(u9c_, ensure_ascii=False)
        add(db, logData)
